//
//  ReservationFlowView.swift
//  CMB250716
//
//  Created by Assistant on 2025-01-02.
//

import SwiftUI
import UIKit

/// 预订流程视图 - 现代化设计
struct ReservationFlowView: View {
    @EnvironmentObject var dataManager: DataManager
    @Binding var isPresented: Bool
    let onReservationConfirmed: (ReservationConfig.ReservationInfo) -> Void
    let onImmediateDineIn: (() -> Void)?
    let onImmediateTakeAway: (() -> Void)?
    
    // MARK: - 订单类型
    @State private var selectedOrderType: OrderType = .immediatelyDineIn
    
    // MARK: - 预订信息
    @State private var partySizeText: String = "2"
    @State private var selectedSeatingType: ReservationConfig.SeatingType = .indoor
    @State private var selectedDate: Date = Date()
    @State private var selectedTime: Date?
    @State private var specialRequests: String = ""
    @State private var availableTimes: [Date] = []
    @State private var disclaimerAccepted = false
    
    // MARK: - UI状态
    @State private var showingDatePicker = false
    @State private var showingDisclaimer = false
    @State private var timelineScrollPosition: CGFloat = 0
    @State private var selectedHour: Int = Calendar.current.component(.hour, from: Date())
    @State private var selectedMinute: Int = 0
    @State private var availableDates: [Date] = []
    @State private var selectedDateIndex: Int = 0
    @State private var showingTimeSuggestion = false
    @State private var suggestedTime: Date?
    @State private var timeSuggestionMessage = ""
    @State private var showingSeatAvailabilityWarning = false
    @State private var seatAvailabilityWarningMessage = ""
    @State private var showingBusinessHoursWarning = false
    @State private var businessHoursWarningMessage = ""
    
    // MARK: - 计算属性
    private var selectedPartySize: Int {
        Int(partySizeText) ?? 2
    }
    
    // 根据座位类型获取最大人数限制
    private var maxPartySizeForSelectedSeating: Int {
        if selectedOrderType.isDineIn {
            return selectedSeatingType == .indoor ? ReservationConfig.IndoorSeating.totalSeats : ReservationConfig.OutdoorSeating.totalSeats
        } else {
            // 外带订单不受座位限制
            return 50
        }
    }
    
    private var shouldShowPartySizeAndSeating: Bool {
        selectedOrderType.isReservation && selectedOrderType.isDineIn
    }
    
    private var canConfirmReservation: Bool {
        if !selectedOrderType.isReservation {
            return true
        }
        
        let hasRequiredInfo = selectedTime != nil
        let hasValidPartySize = shouldShowPartySizeAndSeating ? selectedPartySize >= 1 : true
        return hasRequiredInfo && hasValidPartySize && disclaimerAccepted
    }
    
    /// 订单类型枚举
    enum OrderType: String, CaseIterable, Identifiable {
        case immediatelyDineIn = "immediately_dine_in"
        case immediatelyTakeAway = "immediately_takeaway"
        case reservationDineIn = "reservation_dine_in"
        case reservationTakeAway = "reservation_takeaway"
        
        var id: String { rawValue }
        
        var isReservation: Bool {
            switch self {
            case .reservationDineIn, .reservationTakeAway:
                return true
            case .immediatelyDineIn, .immediatelyTakeAway:
                return false
            }
        }
        
        var isDineIn: Bool {
            switch self {
            case .immediatelyDineIn, .reservationDineIn:
                return true
            case .immediatelyTakeAway, .reservationTakeAway:
                return false
            }
        }
        
        var title_zh: String {
            switch self {
            case .immediatelyDineIn:
                return "立即堂食"
            case .immediatelyTakeAway:
                return "立即外带"
            case .reservationDineIn:
                return "预订\n堂食"
            case .reservationTakeAway:
                return "预订外带"
            }
        }
        
        var title_en: String {
            switch self {
            case .immediatelyDineIn:
                return "Dine-in Now"
            case .immediatelyTakeAway:
                return "Take Away Now"
            case .reservationDineIn:
                return "Reserve\nDine-in"
            case .reservationTakeAway:
                return "Reserve Take Away"
            }
        }
        
        var iconName: String {
            switch self {
            case .immediatelyDineIn:
                return "qrcode.viewfinder"
            case .immediatelyTakeAway:
                return "bag.fill"
            case .reservationDineIn:
                return "calendar.badge.plus"
            case .reservationTakeAway:
                return "calendar.badge.clock"
            }
        }
        
        var color: Color {
            switch self {
            case .immediatelyDineIn:
                return .orange
            case .immediatelyTakeAway:
                return .green
            case .reservationDineIn:
                return .blue
            case .reservationTakeAway:
                return .purple
            }
        }
    }
    
    var body: some View {
        NavigationView {
            ZStack {
                // 现代化背景渐变
                LinearGradient(
                    colors: [
                        Color(red: 0.02, green: 0.02, blue: 0.05),
                        Color(red: 0.08, green: 0.08, blue: 0.12),
                        Color(red: 0.15, green: 0.13, blue: 0.18),
                        Color(red: 0.22, green: 0.18, blue: 0.25)
                    ],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
                
                // 统一滚动视图 - 移除固定底部栏
                ScrollViewReader { proxy in
                    ScrollView {
                        VStack(spacing: 16) {
                            // 现代化标题区域
                            modernHeaderSection
                            
                            // 重新设计的订单类型选择
                            modernOrderTypeSection
                            
                            // 预订信息区域 - 仅在预订类型时显示
                            if selectedOrderType.isReservation {
                                modernReservationInfoSection
                                    .id("dateTimeSection") // 添加ID用于滚动定位
                            }
                            
                            // 重新设计的免责声明区域 - 仅在预订类型时显示
                            if selectedOrderType.isReservation {
                                modernDisclaimerSection
                            }
                            
                            // 底部确认按钮区域 - 现在在滚动视图内
                            // 只有预订服务才显示底部确认按钮
                            if selectedOrderType.isReservation {
                                VStack(spacing: 10) {
                                    // 预订摘要（仅预订类型且同意条款后显示）
                                    if selectedOrderType.isReservation && selectedTime != nil && disclaimerAccepted {
                                        VStack(spacing: 8) {
                                            HStack {
                                                Text(dataManager.currentLanguage == "zh" ? "预订摘要" : "Reservation Summary")
                                                    .font(.system(size: 18, weight: .bold, design: .rounded))
                                                    .foregroundColor(.white)
                                                Spacer()
                                                
                                                Button(action: {
                                                    // 重置条款同意状态，隐藏预订摘要
                                                    disclaimerAccepted = false
                                                    // 滚动到日期时间选择区域
                                                    withAnimation(.easeInOut(duration: 0.8)) {
                                                        proxy.scrollTo("dateTimeSection", anchor: .center)
                                                    }
                                                }) {
                                                    Text(dataManager.currentLanguage == "zh" ? "变更" : "Change")
                                                        .font(.system(size: 14, weight: .medium, design: .rounded))
                                                        .foregroundColor(.orange)
                                                        .padding(.horizontal, 12)
                                                        .padding(.vertical, 6)
                                                        .background(
                                                            RoundedRectangle(cornerRadius: 8)
                                                                .fill(Color.orange.opacity(0.15))
                                                                .overlay(
                                                                    RoundedRectangle(cornerRadius: 8)
                                                                        .stroke(Color.orange.opacity(0.3), lineWidth: 1)
                                                                )
                                                        )
                                                }
                                            }
                                            
                                            VStack(spacing: 6) {
                                                // 预订类型
                                                summaryRow(
                                                    dataManager.currentLanguage == "zh" ? "预订类型" : "Reservation Type",
                                                    dataManager.currentLanguage == "zh" ? selectedOrderType.title_zh : selectedOrderType.title_en
                                                )
                                                
                                                if shouldShowPartySizeAndSeating {
                                                    summaryRow(
                                                        dataManager.currentLanguage == "zh" ? "用餐人数" : "Party Size",
                                                        dataManager.currentLanguage == "zh" ? "\(selectedPartySize)人" : "\(selectedPartySize)"
                                                    )
                                                    summaryRow(
                                                        dataManager.currentLanguage == "zh" ? "座位类型" : "Seating Type",
                                                        dataManager.currentLanguage == "zh" ? selectedSeatingType.chineseName : selectedSeatingType.englishName
                                                    )
                                                }
                                                summaryRow(
                                                    dataManager.currentLanguage == "zh" ? "日期" : "Date",
                                                    formatDate(selectedDate)
                                                )
                                                if let time = selectedTime {
                                                    summaryRow(
                                                        dataManager.currentLanguage == "zh" ? "时间" : "Time",
                                                        formatTime(time)
                                                    )
                                                }
                                                if !specialRequests.isEmpty {
                                                    summaryRow(
                                                        dataManager.currentLanguage == "zh" ? "特殊要求" : "Special Requests",
                                                        specialRequests
                                                    )
                                                }
                                            }
                                        }
                                        .padding(20)
                                        .background(
                                            RoundedRectangle(cornerRadius: 20)
                                                .fill(
                                                    LinearGradient(
                                                        colors: [
                                                            Color.orange.opacity(0.15),
                                                            Color.orange.opacity(0.08),
                                                            Color.orange.opacity(0.05)
                                                        ],
                                                        startPoint: .topLeading,
                                                        endPoint: .bottomTrailing
                                                    )
                                                )
                                                .overlay(
                                                    RoundedRectangle(cornerRadius: 20)
                                                        .stroke(
                                                            LinearGradient(
                                                                colors: [Color.orange.opacity(0.4), Color.orange.opacity(0.2)],
                                                                startPoint: .topLeading,
                                                                endPoint: .bottomTrailing
                                                            ),
                                                            lineWidth: 1
                                                        )
                                                )
                                        )
                                    }
                                    
                                    // 确认按钮
                                    Button(action: {
                                        handleConfirmAction()
                                    }) {
                                        HStack {
                                            Image(systemName: "checkmark.circle.fill")
                                                .font(.system(size: 20, weight: .bold))
                                            Text(dataManager.currentLanguage == "zh" ? "确认预订" : "Confirm Reservation")
                                                .font(.system(size: 16, weight: .bold, design: .rounded))
                                        }
                                        .foregroundColor(.white)
                                        .frame(maxWidth: .infinity)
                                        .frame(height: 56)
                                        .background(
                                            canConfirmReservation ?
                                            LinearGradient(
                                                colors: [
                                                    selectedOrderType.color,
                                                    selectedOrderType.color.opacity(0.8),
                                                    selectedOrderType.color.opacity(0.9)
                                                ],
                                                startPoint: .topLeading,
                                                endPoint: .bottomTrailing
                                            ) :
                                            LinearGradient(
                                                colors: [Color.gray.opacity(0.6), Color.gray.opacity(0.4)],
                                                startPoint: .topLeading,
                                                endPoint: .bottomTrailing
                                            )
                                        )
                                        .overlay(
                                            RoundedRectangle(cornerRadius: 20)
                                                .stroke(
                                                    canConfirmReservation ?
                                                    LinearGradient(
                                                        colors: [selectedOrderType.color.opacity(0.8), selectedOrderType.color.opacity(0.4)],
                                                        startPoint: .topLeading,
                                                        endPoint: .bottomTrailing
                                                    ) :
                                                    LinearGradient(
                                                        colors: [Color.gray.opacity(0.4), Color.gray.opacity(0.2)],
                                                        startPoint: .topLeading,
                                                        endPoint: .bottomTrailing
                                                    ),
                                                    lineWidth: 2
                                                )
                                        )
                                        .cornerRadius(20)
                                        .shadow(
                                            color: canConfirmReservation ? selectedOrderType.color.opacity(0.4) : .clear,
                                            radius: canConfirmReservation ? 15 : 0,
                                            x: 0,
                                            y: canConfirmReservation ? 8 : 0
                                        )
                                    }
                                    .disabled(!canConfirmReservation)
                                    .scaleEffect(canConfirmReservation ? 1.0 : 0.98)
                                    .animation(.spring(response: 0.3, dampingFraction: 0.7), value: canConfirmReservation)
                                }
                                .padding(.horizontal, 4)
                                .frame(maxWidth: .infinity)
                            }
                            
                            // 底部安全区域
                            Spacer(minLength: 50)
                        }
                        .frame(maxWidth: .infinity)
                        .padding(.horizontal, 20)
                        .padding(.top, 20)
                    }
                    .frame(maxWidth: .infinity)
                }
                
                // 时间建议弹窗
                if showingTimeSuggestion {
                    timeSuggestionOverlay
                }
                
                if showingSeatAvailabilityWarning {
                    seatAvailabilityWarningOverlay
                }
                
                if showingBusinessHoursWarning {
                    businessHoursWarningOverlay
                }
            }
        }
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .navigationBarLeading) {
                Button(dataManager.currentLanguage == "zh" ? "取消" : "Cancel") {
                    isPresented = false
                }
                .foregroundColor(.orange)
                .font(.system(size: 16, weight: .medium))
            }
            
            ToolbarItem(placement: .principal) {
                Text(dataManager.currentLanguage == "zh" ? "预订服务" : "Reservation Service")
                    .font(.system(size: 18, weight: .semibold, design: .rounded))
                    .foregroundColor(.white)
            }
        }
        .onAppear {
            initializeAvailableDates()
            loadAvailableTimes()
            // 设置默认的第一个可用时间
            setDefaultAvailableTime()
        }
        .onChange(of: selectedDate) { _ in
            loadAvailableTimes()
        }
        .onChange(of: selectedSeatingType) { _ in
            loadAvailableTimes()
        }
        .sheet(isPresented: $showingDisclaimer) {
            DisclaimerView(isAccepted: $disclaimerAccepted)
                .environmentObject(dataManager)
        }
    }
    
    // MARK: - 现代化标题区域（已移除，Logo移至服务选择区域）
    private var modernHeaderSection: some View {
        EmptyView()
    }
    
    // MARK: - 现代化订单类型选择
    private var modernOrderTypeSection: some View {
        VStack(spacing: 24) {
            // 立即服务组
            VStack(spacing: 20) {
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? ReservationConfig.Localization.immediateServiceGroup_zh : ReservationConfig.Localization.immediateServiceGroup_en)
                        .font(.system(size: 18, weight: .bold, design: .rounded))
                        .foregroundColor(.white)
                    
                    Spacer()
                    
                    // Cu Mr Bull Logo - 移至右侧
                    Image("Logo")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 60, height: 60)
                        .shadow(color: .orange.opacity(0.3), radius: 5, x: 0, y: 2)
                }
                
                HStack(spacing: 16) {
                    modernOrderTypeCard(.immediatelyDineIn)
                        .frame(maxWidth: .infinity)
                    modernOrderTypeCard(.immediatelyTakeAway)
                        .frame(maxWidth: .infinity)
                }
                .frame(maxWidth: .infinity)
                
                // 立即服务按钮 - 在选择立即服务时显示
                if !selectedOrderType.isReservation {
                    Button(action: {
                        handleConfirmAction()
                    }) {
                        HStack {
                            Image(systemName: selectedOrderType.isDineIn ? "qrcode.viewfinder" : "bag.fill")
                                .font(.system(size: 20, weight: .bold))
                            Text(selectedOrderType.isDineIn ? 
                                (dataManager.currentLanguage == "zh" ? "请扫码桌子上的二维码" : "Please scan the QR code on your table") : 
                                (dataManager.currentLanguage == "zh" ? "立即下单" : "Order Now")
                            )
                                .font(.system(size: 16, weight: .bold, design: .rounded))
                        }
                        .foregroundColor(.white)
                        .frame(maxWidth: .infinity)
                        .frame(height: 50)
                        .background(
                            LinearGradient(
                                colors: [
                                    selectedOrderType.color,
                                    selectedOrderType.color.opacity(0.8),
                                    selectedOrderType.color.opacity(0.9)
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .cornerRadius(16)
                        .shadow(color: selectedOrderType.color.opacity(0.3), radius: 8, x: 0, y: 4)
                    }
                    .padding(.top, 8)
                }
                

            }
            .padding(24)
            .background(modernCardBackground)
            
            // 预定服务组
            VStack(spacing: 20) {
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? ReservationConfig.Localization.reservationServiceGroup_zh : ReservationConfig.Localization.reservationServiceGroup_en)
                        .font(.system(size: 18, weight: .bold, design: .rounded))
                        .foregroundColor(.white)
                    Spacer()
                }
                
                HStack(spacing: 16) {
                    modernOrderTypeCard(.reservationDineIn)
                        .frame(maxWidth: .infinity)
                    modernOrderTypeCard(.reservationTakeAway)
                        .frame(maxWidth: .infinity)
                }
                .frame(maxWidth: .infinity)
            }
            .padding(24)
            .background(modernCardBackground)
        }
    }
    
    private func modernOrderTypeCard(_ orderType: OrderType) -> some View {
        Button(action: {
            withAnimation(.spring(response: 0.5, dampingFraction: 0.7)) {
                selectedOrderType = orderType
                if !orderType.isReservation {
                    selectedTime = nil
                    disclaimerAccepted = false
                } else if orderType == .reservationDineIn {
                    // 当选择预订堂食时，立即检查默认时间的座位可用性
                    checkAndSetDefaultTimeForReservation()
                }
            }
        }) {
            VStack(spacing: 20) {
                // 现代化图标设计
                ZStack {
                    // 背景圆形
                    Circle()
                        .fill(
                            selectedOrderType == orderType ?
                            LinearGradient(
                                colors: [orderType.color, orderType.color.opacity(0.6)],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            ) :
                            LinearGradient(
                                colors: [Color.white.opacity(0.15), Color.white.opacity(0.08)],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .frame(width: 60, height: 60)
                        .overlay(
                            Circle()
                                .stroke(
                                    selectedOrderType == orderType ? 
                                    orderType.color.opacity(0.5) : 
                                    Color.white.opacity(0.2),
                                    lineWidth: 2
                                )
                        )
                    
                    Image(systemName: orderType.iconName)
                        .font(.system(size: 24, weight: .semibold))
                        .foregroundColor(selectedOrderType == orderType ? .white : orderType.color)
                }
                
                // 标题文字
                Text(dataManager.currentLanguage == "zh" ? orderType.title_zh : orderType.title_en)
                    .font(.system(size: 16, weight: .bold, design: .rounded))
                    .foregroundColor(.white)
                    .multilineTextAlignment(.center)
                    .lineLimit(2)
            }
            .frame(maxWidth: .infinity)
            .frame(height: 160)
            .frame(minWidth: 0) // 确保卡片可以收缩
            .background(
                RoundedRectangle(cornerRadius: 24)
                    .fill(
                        selectedOrderType == orderType ?
                        LinearGradient(
                            colors: [
                                orderType.color.opacity(0.25),
                                orderType.color.opacity(0.15),
                                orderType.color.opacity(0.05)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        ) :
                        LinearGradient(
                            colors: [
                                Color.white.opacity(0.12),
                                Color.white.opacity(0.08),
                                Color.black.opacity(0.1)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .overlay(
                        RoundedRectangle(cornerRadius: 24)
                            .stroke(
                                selectedOrderType == orderType ? 
                                LinearGradient(
                                    colors: [orderType.color.opacity(0.6), orderType.color.opacity(0.3)],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                ) :
                                LinearGradient(
                                    colors: [Color.white.opacity(0.25), Color.white.opacity(0.1)],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                ),
                                lineWidth: selectedOrderType == orderType ? 2 : 1
                            )
                    )
                    .shadow(
                        color: selectedOrderType == orderType ? orderType.color.opacity(0.4) : Color.black.opacity(0.1),
                        radius: selectedOrderType == orderType ? 15 : 8,
                        x: 0,
                        y: selectedOrderType == orderType ? 8 : 4
                    )
            )
            .scaleEffect(selectedOrderType == orderType ? 1.02 : 1.0) // 减小缩放比例避免超出屏幕
        }
        .buttonStyle(PlainButtonStyle())
    }
    
    // MARK: - 现代化预订信息区域
    private var modernReservationInfoSection: some View {
        VStack(spacing: 7) {
            // 区域标题
            HStack {
                Text(dataManager.currentLanguage == "zh" ? "预订详情" : "Reservation Details")
                    .font(.system(size: 16, weight: .semibold, design: .rounded))
                    .foregroundColor(.white)
                Spacer()
            }
            
            VStack(spacing: 12) {
                // 用餐人数和座位类型
                if shouldShowPartySizeAndSeating {
                    modernPartySizeAndSeatingSection
                }
                
                // 现代化日期时间选择
                modernDateTimeSection
                
                // 特殊要求
                modernSpecialRequestsSection
            }
        }
        .padding(.horizontal, 20)
        .padding(.vertical, 7)
        .frame(maxWidth: .infinity)
        .background(modernCardBackground)
    }
    
    // MARK: - 现代化用餐人数和座位类型
    private var modernPartySizeAndSeatingSection: some View {
        VStack(spacing: 10) {
            HStack(spacing: 12) {
                // 用餐人数部分 - 左半部，带边框
                VStack(spacing: 8) {
                    VStack(spacing: 8) {
                        HStack {
                            Spacer()
                            Image(systemName: "person.2.fill")
                                .font(.system(size: 16, weight: .semibold))
                                .foregroundColor(.white)
                            Spacer()
                        }
                        
                        HStack {
                            Spacer()
                            Text(dataManager.currentLanguage == "zh" ? "用餐人数" : "Party Size")
                            .font(.system(size: 16, weight: .semibold, design: .rounded))
                            .foregroundColor(.white)
                            Spacer()
                        }
                    }
                    
                    HStack(spacing: 8) {
                        // 减少按钮
                        Button(action: {
                            if selectedPartySize > 1 {
                                partySizeText = String(selectedPartySize - 1)
                            }
                        }) {
                            Image(systemName: "minus.circle.fill")
                                .font(.system(size: 20))
                                .foregroundColor(selectedPartySize > 1 ? .orange : .gray)
                        }
                        .disabled(selectedPartySize <= 1)
                        
                        // 人数显示
                        Text(dataManager.currentLanguage == "zh" ? "\(selectedPartySize)人" : "\(selectedPartySize)")
                            .font(.system(size: 16, weight: .bold, design: .rounded))
                            .foregroundColor(.white)
                            .frame(minWidth: 50)
                            .padding(.vertical, 6)
                            .background(
                                RoundedRectangle(cornerRadius: 12)
                                    .fill(Color.white.opacity(0.1))
                                    .overlay(
                                        RoundedRectangle(cornerRadius: 12)
                                            .stroke(Color.orange.opacity(0.5), lineWidth: 1)
                                    )
                            )
                        
                        // 增加按钮
                        Button(action: {
                            if selectedPartySize < maxPartySizeForSelectedSeating {
                                let newPartySize = selectedPartySize + 1
                                partySizeText = String(newPartySize)
                                checkSeatAvailabilityForCurrentSelection()
                            }
                        }) {
                            Image(systemName: "plus.circle.fill")
                                .font(.system(size: 20))
                                .foregroundColor(selectedPartySize < maxPartySizeForSelectedSeating ? .orange : .gray)
                        }
                        .disabled(selectedPartySize >= maxPartySizeForSelectedSeating)
                    }
                }
                .frame(maxWidth: .infinity)
                .frame(minHeight: 120) // 设置最小高度以匹配Seating Preference卡片
                .padding(20)
                .background(
                    RoundedRectangle(cornerRadius: 16)
                        .fill(
                            LinearGradient(
                                colors: [
                                    Color.white.opacity(0.12),
                                    Color.white.opacity(0.08),
                                    Color.white.opacity(0.05)
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .overlay(
                            RoundedRectangle(cornerRadius: 16)
                                .stroke(
                                    LinearGradient(
                                        colors: [Color.orange.opacity(0.4), Color.orange.opacity(0.2)],
                                        startPoint: .topLeading,
                                        endPoint: .bottomTrailing
                                    ),
                                    lineWidth: 1
                                )
                        )
                )
                .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
                
                // 座位偏好部分 - 右半部，带边框
                VStack(spacing: 6) {
                    HStack {
                        Spacer()
                        Text(dataManager.currentLanguage == "zh" ? "座位偏好" : "Seating Preference")
                            .font(.system(size: 16, weight: .semibold, design: .rounded))
                            .foregroundColor(.white)
                        Spacer()
                    }
                    
                    VStack(spacing: 3) {
                        ForEach(ReservationConfig.SeatingType.allCases) { seatingType in
                            Button(action: {
                                withAnimation(.spring(response: 0.3, dampingFraction: 0.7)) {
                                    selectedSeatingType = seatingType
                                    // 检查当前人数是否超过新座位类型的限制
                                    let newMaxPartySize = seatingType == .indoor ? ReservationConfig.IndoorSeating.totalSeats : ReservationConfig.OutdoorSeating.totalSeats
                                    if selectedPartySize > newMaxPartySize {
                                        partySizeText = String(newMaxPartySize)
                                    }
                                    checkSeatAvailabilityForCurrentSelection()
                                }
                            }) {
                                HStack(spacing: 6) {
                                    Image(systemName: seatingType.iconName)
                                        .font(.system(size: 12, weight: .semibold))
                                        .foregroundColor(selectedSeatingType == seatingType ? .white : seatingType == .indoor ? .blue : .green)
                                    
                                    Text(dataManager.currentLanguage == "zh" ? seatingType.chineseName : seatingType.englishName)
                                        .font(.system(size: 12, weight: .medium, design: .rounded))
                                        .foregroundColor(.white)
                                    
                                    Spacer()
                                }
                                .padding(.horizontal, 6)
                                .padding(.vertical, 4)
                                .frame(height: 26)
                                .frame(maxWidth: .infinity)
                                .background(
                                    RoundedRectangle(cornerRadius: 8)
                                        .fill(
                                            selectedSeatingType == seatingType ?
                                            LinearGradient(
                                                colors: [seatingType == .indoor ? Color.blue.opacity(0.3) : Color.green.opacity(0.3), seatingType == .indoor ? Color.blue.opacity(0.2) : Color.green.opacity(0.2)],
                                                startPoint: .topLeading,
                                                endPoint: .bottomTrailing
                                            ) :
                                            LinearGradient(
                                                colors: [Color.white.opacity(0.1), Color.white.opacity(0.05)],
                                                startPoint: .topLeading,
                                                endPoint: .bottomTrailing
                                            )
                                        )
                                        .overlay(
                                            RoundedRectangle(cornerRadius: 8)
                                                .stroke(
                                                    selectedSeatingType == seatingType ? 
                                                    (seatingType == .indoor ? Color.blue.opacity(0.6) : Color.green.opacity(0.6)) : 
                                                    Color.white.opacity(0.2),
                                                    lineWidth: 1
                                                )
                                        )
                                )
                            }
                            .buttonStyle(PlainButtonStyle())
                        }
                    }
                }
                .frame(maxWidth: .infinity)
                .frame(minHeight: 120) // 设置最小高度以匹配Party Size卡片
                .padding(20)
                .background(
                    RoundedRectangle(cornerRadius: 16)
                        .fill(
                            LinearGradient(
                                colors: [
                                    Color.white.opacity(0.12),
                                    Color.white.opacity(0.08),
                                    Color.white.opacity(0.05)
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .overlay(
                            RoundedRectangle(cornerRadius: 16)
                                .stroke(
                                    LinearGradient(
                                        colors: [Color.orange.opacity(0.4), Color.orange.opacity(0.2)],
                                        startPoint: .topLeading,
                                        endPoint: .bottomTrailing
                                    ),
                                    lineWidth: 1
                                )
                        )
                )
                .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
            }
            .frame(maxWidth: .infinity)
        }
        .frame(maxWidth: .infinity)
    }
    
    // MARK: - 保留原有的用餐人数部分（备用）
    private var modernPartySizeSection_backup: some View {
        VStack(spacing: 16) {
            HStack {
                Label("用餐人数", systemImage: "person.2.fill")
                    .font(.system(size: 16, weight: .semibold, design: .rounded))
                    .foregroundColor(.white)
                Spacer()
            }
            
            HStack(spacing: 16) {
                // 减少按钮
                Button(action: {
                    if selectedPartySize > 1 {
                        partySizeText = String(selectedPartySize - 1)
                    }
                }) {
                    Image(systemName: "minus.circle.fill")
                        .font(.system(size: 24))
                        .foregroundColor(selectedPartySize > 1 ? .orange : .gray)
                }
                .disabled(selectedPartySize <= 1)
                
                // 人数显示
                Text("\(selectedPartySize)人")
                    .font(.system(size: 20, weight: .bold, design: .rounded))
                    .foregroundColor(.white)
                    .frame(minWidth: 80)
                    .padding(.vertical, 12)
                    .background(
                        RoundedRectangle(cornerRadius: 12)
                            .fill(Color.white.opacity(0.1))
                            .overlay(
                                RoundedRectangle(cornerRadius: 12)
                                    .stroke(Color.orange.opacity(0.5), lineWidth: 1)
                            )
                    )
                
                // 增加按钮
                Button(action: {
                    if selectedPartySize < 20 {
                        partySizeText = String(selectedPartySize + 1)
                    }
                }) {
                    Image(systemName: "plus.circle.fill")
                        .font(.system(size: 24))
                        .foregroundColor(selectedPartySize < 20 ? .orange : .gray)
                }
                .disabled(selectedPartySize >= 20)
                
                Spacer()
            }
        }
    }
    
    // MARK: - 保留原有的座位类型部分（备用）
    private var modernSeatingTypeSection_backup: some View {
        VStack(spacing: 16) {
            HStack {
                Text("座位偏好")
                    .font(.system(size: 16, weight: .semibold, design: .rounded))
                    .foregroundColor(.white)
                Spacer()
            }
            
            HStack(spacing: 12) {
                ForEach([ReservationConfig.SeatingType.indoor, ReservationConfig.SeatingType.outdoor], id: \.self) { seatingType in
                    Button(action: {
                        withAnimation(.spring(response: 0.3, dampingFraction: 0.7)) {
                            selectedSeatingType = seatingType
                        }
                    }) {
                        Text(seatingType.chineseName)
                            .font(.system(size: 16, weight: .semibold, design: .rounded))
                            .foregroundColor(selectedSeatingType == seatingType ? .white : .white.opacity(0.7))
                            .frame(maxWidth: .infinity)
                            .padding(.vertical, 16)
                            .background(
                                RoundedRectangle(cornerRadius: 16)
                                    .fill(
                                        selectedSeatingType == seatingType ?
                                        LinearGradient(
                                            colors: [.orange, .orange.opacity(0.8)],
                                            startPoint: .topLeading,
                                            endPoint: .bottomTrailing
                                        ) :
                                        LinearGradient(
                                            colors: [Color.white.opacity(0.1), Color.white.opacity(0.05)],
                                            startPoint: .topLeading,
                                            endPoint: .bottomTrailing
                                        )
                                    )
                                    .overlay(
                                        RoundedRectangle(cornerRadius: 16)
                                            .stroke(
                                                selectedSeatingType == seatingType ? 
                                                Color.orange.opacity(0.6) : 
                                                Color.white.opacity(0.2),
                                                lineWidth: 1
                                            )
                                    )
                            )
                            .scaleEffect(selectedSeatingType == seatingType ? 1.02 : 1.0)
                    }
                    .buttonStyle(PlainButtonStyle())
                }
            }
        }
    }
    
    // MARK: - 现代化日期时间选择
    private var modernDateTimeSection: some View {
        VStack(spacing: 10) {
            // 重新设计的时间和日期选择器 - 统一框体内，类似时间轴样式
            VStack(spacing: 8) {
                // 时间和日期选择器水平布局 - 统一容器
                HStack(spacing: 8) {
                    // 时间选择器（左侧）- 改为10分钟间隔的时间轴样式
                    VStack(spacing: 4) {
                        Text(dataManager.currentLanguage == "zh" ? "时间" : "Time")
                            .font(.system(size: 14, weight: .semibold, design: .rounded))
                            .foregroundColor(.white)
                        
                        Picker("时间", selection: Binding(
                            get: { 
                                let availableSlots = getAvailableTimeSlots()
                                let currentSelection = selectedHour * 60 + selectedMinute
                                // 如果当前选择不在可用时间段中，返回第一个可用时间段
                                return availableSlots.contains(currentSelection) ? currentSelection : (availableSlots.first ?? currentSelection)
                            },
                            set: { totalMinutes in
                                selectedHour = totalMinutes / 60
                                selectedMinute = totalMinutes % 60
                                updateSelectedTime()
                            }
                        )) {
                            ForEach(getAvailableTimeSlots(), id: \.self) { timeSlot in
                                Text(formatTimeSlot(timeSlot))
                                    .font(.system(size: 14, weight: .medium, design: .rounded))
                                    .foregroundColor(.white)
                                    .tag(timeSlot)
                            }
                        }
                        .pickerStyle(WheelPickerStyle())
                        .frame(width: 90, height: 100)
                        .clipped()
                    }
                    .frame(maxWidth: .infinity)
                    
                    // 分隔线
                    Rectangle()
                        .fill(Color.white.opacity(0.2))
                        .frame(width: 1, height: 80)
                    
                    // 日期选择器（右侧）- 改为类似时间轴的样式
                    VStack(spacing: 4) {
                        Text(dataManager.currentLanguage == "zh" ? "日期" : "Date")
                            .font(.system(size: 14, weight: .semibold, design: .rounded))
                            .foregroundColor(.white)
                        
                        Picker("日期", selection: $selectedDateIndex) {
                            ForEach(0..<availableDates.count, id: \.self) { index in
                                Text(formatDateForPicker(availableDates[index]))
                                    .font(.system(size: 14, weight: .medium, design: .rounded))
                                    .foregroundColor(.white)
                                    .tag(index)
                            }
                        }
                        .pickerStyle(WheelPickerStyle())
                        .frame(width: 120, height: 100)
                        .clipped()
                        .onChange(of: selectedDateIndex) { newIndex in
                            if newIndex < availableDates.count {
                                selectedDate = availableDates[newIndex]
                                // 当日期改变时，自动设置为第一个可用时间
                                let availableSlots = getAvailableTimeSlots()
                                if let firstAvailableSlot = availableSlots.first {
                                    selectedHour = firstAvailableSlot / 60
                                    selectedMinute = firstAvailableSlot % 60
                                }
                                updateSelectedTime()
                            }
                        }
                    }
                    .frame(maxWidth: .infinity)
                }
                .padding(10)
                .background(
                    RoundedRectangle(cornerRadius: 16)
                        .fill(
                            LinearGradient(
                                colors: [
                                    Color.white.opacity(0.12),
                                    Color.white.opacity(0.08),
                                    Color.white.opacity(0.05)
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .overlay(
                            RoundedRectangle(cornerRadius: 16)
                                .stroke(
                                    LinearGradient(
                                        colors: [Color.orange.opacity(0.4), Color.orange.opacity(0.2)],
                                        startPoint: .topLeading,
                                        endPoint: .bottomTrailing
                                    ),
                                    lineWidth: 1
                                )
                        )
                )
                .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
            }
        }
    }
    
    // MARK: - 现代化特殊要求
    private var modernSpecialRequestsSection: some View {
        VStack(spacing: 8) {
            HStack {
                Text(dataManager.currentLanguage == "zh" ? "特殊要求" : "Special Requests")
                    .font(.system(size: 16, weight: .semibold, design: .rounded))
                    .foregroundColor(.white)
                Spacer()
                Text(dataManager.currentLanguage == "zh" ? "选填" : "Optional")
                    .font(.system(size: 12, weight: .medium, design: .rounded))
                    .foregroundColor(.white.opacity(0.5))
            }
            
            TextField(dataManager.currentLanguage == "zh" ? "请输入特殊要求（如过敏信息、座位偏好等）" : "Enter special requests (allergies, seating preferences, etc.)", text: $specialRequests, axis: .vertical)
                .font(.system(size: 14, weight: .medium, design: .rounded))
                .foregroundColor(.white)
                .padding(8)
                .background(
                    RoundedRectangle(cornerRadius: 16)
                        .fill(Color.white.opacity(0.1))
                        .overlay(
                            RoundedRectangle(cornerRadius: 16)
                                .stroke(Color.white.opacity(0.2), lineWidth: 1)
                        )
                )
                .lineLimit(3...6)
                .frame(maxWidth: .infinity)
        }
        .frame(maxWidth: .infinity)
    }
    
    // MARK: - 现代化免责声明区域
    private var modernDisclaimerSection: some View {
        VStack(spacing: 10) {
            HStack {
                Text(dataManager.currentLanguage == "zh" ? "预订条款" : "Reservation Terms")
                    .font(.system(size: 20, weight: .bold, design: .rounded))
                    .foregroundColor(.white)
                Spacer()
            }
            
            VStack(spacing: 8) {
                // 条款列表
                VStack(spacing: 6) {
                    let terms = dataManager.currentLanguage == "zh" ? ReservationConfig.Localization.reservationTerms_zh : ReservationConfig.Localization.reservationTerms_en
                    ForEach(Array(terms.enumerated()), id: \.offset) { index, term in
                        HStack(alignment: .top, spacing: 8) {
                            Text("\(index + 1).")
                                .font(.system(size: 14, weight: .medium, design: .rounded))
                                .foregroundColor(.white.opacity(0.8))
                                .frame(width: 20, alignment: .leading)
                            
                            Text(term)
                                .font(.system(size: 14, weight: .medium, design: .rounded))
                                .foregroundColor(.white.opacity(0.8))
                                .multilineTextAlignment(.leading)
                                .fixedSize(horizontal: false, vertical: true)
                            
                            Spacer()
                        }
                    }
                }
                
                // 同意条款按钮
                Button(action: {
                    withAnimation(.spring(response: 0.3, dampingFraction: 0.7)) {
                        disclaimerAccepted.toggle()
                    }
                }) {
                    HStack(spacing: 12) {
                        Image(systemName: disclaimerAccepted ? "checkmark.circle.fill" : "circle")
                            .font(.system(size: 20, weight: .semibold))
                            .foregroundColor(disclaimerAccepted ? .orange : .white.opacity(0.5))
                        
                        Text(dataManager.currentLanguage == "zh" ? "我已阅读并同意以上预订条款" : "I have read and agree to the reservation terms")
                            .font(.system(size: 16, weight: .medium, design: .rounded))
                            .foregroundColor(.white)
                        
                        Spacer()
                    }
                    .padding(8)
                    .background(
                        RoundedRectangle(cornerRadius: 16)
                            .fill(
                                disclaimerAccepted ?
                                LinearGradient(
                                    colors: [Color.orange.opacity(0.2), Color.orange.opacity(0.1)],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                ) :
                                LinearGradient(
                                    colors: [Color.white.opacity(0.1), Color.white.opacity(0.05)],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )
                            .overlay(
                                RoundedRectangle(cornerRadius: 16)
                                    .stroke(
                                        disclaimerAccepted ? 
                                        Color.orange.opacity(0.5) : 
                                        Color.white.opacity(0.2),
                                        lineWidth: 1
                                    )
                            )
                    )
                }
                .buttonStyle(PlainButtonStyle())
            }
        }
        .padding(.horizontal, 20)
                .padding(.vertical, 14)
        .frame(maxWidth: .infinity)
        .background(modernCardBackground)
    }
    
    private func disclaimerItem(_ text: String) -> some View {
        HStack {
            Text(text)
                .font(.system(size: 14, weight: .medium, design: .rounded))
                .foregroundColor(.white.opacity(0.8))
                .multilineTextAlignment(.leading)
            Spacer()
        }
    }
    
    // MARK: - 现代化确认按钮区域
    private func modernConfirmSectionWithProxy(_ proxy: ScrollViewProxy) -> some View {
        VStack(spacing: 20) {
            // 预订摘要已在主体中内联显示
            
            // 确认按钮
            Button(action: {
                handleConfirmAction()
            }) {
                HStack(spacing: 12) {
                    if canConfirmReservation {
                        Image(systemName: selectedOrderType.isReservation ? "calendar.badge.checkmark" : (selectedOrderType.isDineIn ? "qrcode.viewfinder" : "cart.fill"))
                            .font(.system(size: 20, weight: .semibold))
                    } else {
                        Image(systemName: "exclamationmark.circle")
                            .font(.system(size: 20, weight: .semibold))
                    }
                    
                    Text(selectedOrderType.isReservation ? 
                        (dataManager.currentLanguage == "zh" ? "确认预订" : "Confirm Reservation") : 
                        (dataManager.currentLanguage == "zh" ? "立即下单" : "Order Now"))
                        .font(.system(size: 18, weight: .bold, design: .rounded))
                }
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .frame(height: 60)
                .background(
                    Group {
                        if canConfirmReservation {
                            LinearGradient(
                                colors: [
                                    selectedOrderType.color,
                                    selectedOrderType.color.opacity(0.8),
                                    selectedOrderType.color.opacity(0.9)
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        } else {
                            LinearGradient(
                                colors: [Color.gray.opacity(0.6), Color.gray.opacity(0.4)],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        }
                    }
                )
                .overlay(
                    RoundedRectangle(cornerRadius: 20)
                        .stroke(
                            canConfirmReservation ?
                            LinearGradient(
                                colors: [selectedOrderType.color.opacity(0.8), selectedOrderType.color.opacity(0.4)],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            ) :
                            LinearGradient(
                                colors: [Color.gray.opacity(0.4), Color.gray.opacity(0.2)],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            ),
                            lineWidth: 2
                        )
                )
                .cornerRadius(20)
                .shadow(
                    color: canConfirmReservation ? selectedOrderType.color.opacity(0.4) : .clear,
                    radius: canConfirmReservation ? 15 : 0,
                    x: 0,
                    y: canConfirmReservation ? 8 : 0
                )
            }
            .disabled(!canConfirmReservation)
            .scaleEffect(canConfirmReservation ? 1.0 : 0.98)
            .animation(.spring(response: 0.3, dampingFraction: 0.7), value: canConfirmReservation)
        }
        .padding(.horizontal, 4)
        .frame(maxWidth: .infinity)
    }
    
    private var modernConfirmSection: some View {
        VStack(spacing: 20) {
            // 预订摘要（仅预订类型且同意条款后显示）
            if selectedOrderType.isReservation && selectedTime != nil && disclaimerAccepted {
                // This is kept for compatibility but not used
                EmptyView()
            }
            
            // 确认按钮
            Button(action: {
                handleConfirmAction()
            }) {
                HStack(spacing: 12) {
                    if canConfirmReservation {
                        Image(systemName: selectedOrderType.isReservation ? "calendar.badge.checkmark" : (selectedOrderType.isDineIn ? "qrcode.viewfinder" : "cart.fill"))
                            .font(.system(size: 20, weight: .semibold))
                    } else {
                        Image(systemName: "exclamationmark.circle")
                            .font(.system(size: 20, weight: .semibold))
                    }
                    
                    Text(selectedOrderType.isReservation ? 
                        (dataManager.currentLanguage == "zh" ? "确认预订" : "Confirm Reservation") : 
                        (dataManager.currentLanguage == "zh" ? "立即下单" : "Order Now"))
                        .font(.system(size: 18, weight: .bold, design: .rounded))
                }
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .frame(height: 60)
                .background(
                    Group {
                        if canConfirmReservation {
                            LinearGradient(
                                colors: [
                                    selectedOrderType.color,
                                    selectedOrderType.color.opacity(0.8),
                                    selectedOrderType.color.opacity(0.9)
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        } else {
                            LinearGradient(
                                colors: [Color.gray.opacity(0.6), Color.gray.opacity(0.4)],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        }
                    }
                )
                .overlay(
                    RoundedRectangle(cornerRadius: 20)
                        .stroke(
                            canConfirmReservation ?
                            LinearGradient(
                                colors: [selectedOrderType.color.opacity(0.8), selectedOrderType.color.opacity(0.4)],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            ) :
                            LinearGradient(
                                colors: [Color.gray.opacity(0.4), Color.gray.opacity(0.2)],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            ),
                            lineWidth: 2
                        )
                )
                .cornerRadius(20)
                .shadow(
                    color: canConfirmReservation ? selectedOrderType.color.opacity(0.4) : .clear,
                    radius: canConfirmReservation ? 15 : 0,
                    x: 0,
                    y: canConfirmReservation ? 8 : 0
                )
            }
            .disabled(!canConfirmReservation)
            .scaleEffect(canConfirmReservation ? 1.0 : 0.98)
            .animation(.spring(response: 0.3, dampingFraction: 0.7), value: canConfirmReservation)
        }
        .padding(.horizontal, 4)
        .frame(maxWidth: .infinity)
    }
    
    // MARK: - 现代化预订摘要

    
    private func summaryRow(_ title: String, _ value: String) -> some View {
        HStack {
            Text(title)
                .font(.system(size: 14, weight: .medium, design: .rounded))
                .foregroundColor(.white.opacity(0.8))
            Spacer()
            Text(value)
                .font(.system(size: 14, weight: .semibold, design: .rounded))
                .foregroundColor(.white)
                .multilineTextAlignment(.trailing)
        }
    }
    
    // MARK: - 现代化卡片背景
    private var modernCardBackground: some View {
        RoundedRectangle(cornerRadius: 24)
            .fill(
                LinearGradient(
                    colors: [
                        Color.white.opacity(0.12),
                        Color.white.opacity(0.08),
                        Color.black.opacity(0.1)
                    ],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
            )
            .overlay(
                RoundedRectangle(cornerRadius: 24)
                    .stroke(
                        LinearGradient(
                            colors: [Color.white.opacity(0.25), Color.white.opacity(0.1)],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        ),
                        lineWidth: 1
                    )
            )
            .shadow(color: .black.opacity(0.15), radius: 20, x: 0, y: 10)
    }
    
    // MARK: - 业务逻辑方法
    private func handleConfirmAction() {
        if selectedOrderType.isReservation {
            handleConfirmation()
        } else {
            // 对于立即订单，检查当前是否在营业时间内
            if !BusinessHoursManager.isWithinBusinessHours() {
                // 显示营业时间提示
                let nextOpenTime = BusinessHoursManager.getNextBusinessHour()
                let message: String
                if let nextTime = nextOpenTime {
                    let formatter = DateFormatter()
                    formatter.dateFormat = "HH:mm"
                    let timeString = formatter.string(from: nextTime)
                    message = dataManager.currentLanguage == "zh" ? 
                        "抱歉，现在不是营业时间。下次营业时间：\(timeString)" : 
                        "Sorry, we are currently closed. Next opening time: \(timeString)"
                } else {
                    message = dataManager.currentLanguage == "zh" ? 
                        "抱歉，现在不是营业时间。请查看营业时间或选择预订。" : 
                        "Sorry, we are currently closed. Please check our business hours or make a reservation."
                }
                
                // 显示警告对话框
                showBusinessHoursWarning(message: message)
                return
            }
            
            // 区分立即堂食和立即外带
            if selectedOrderType.isDineIn {
                onImmediateDineIn?()
            } else {
                onImmediateTakeAway?()
            }
            isPresented = false
        }
    }
    
    private func handleConfirmation() {
        guard let selectedTime = selectedTime else { return }
        
        let reservationInfo = ReservationConfig.ReservationInfo(
            partySize: shouldShowPartySizeAndSeating ? selectedPartySize : 1,
            seatingType: shouldShowPartySizeAndSeating ? selectedSeatingType : .indoor,
            reservationTime: selectedTime,
            specialRequests: specialRequests.isEmpty ? nil : specialRequests
        )
        
        onReservationConfirmed(reservationInfo)
        isPresented = false
    }
    
    // MARK: - Time Suggestion Overlay
    
    private var timeSuggestionOverlay: some View {
        ZStack {
            // 半透明背景
            Color.black.opacity(0.4)
                .ignoresSafeArea()
                .onTapGesture {
                    showingTimeSuggestion = false
                }
            
            // 弹窗内容
            VStack(spacing: 20) {
                // 标题
                Text("时间建议")
                    .font(.title2)
                    .fontWeight(.bold)
                    .foregroundColor(.primary)
                
                // 建议消息
                Text(timeSuggestionMessage)
                    .font(.body)
                    .multilineTextAlignment(.center)
                    .foregroundColor(.secondary)
                    .padding(.horizontal)
                
                // 按钮区域
                HStack(spacing: 15) {
                    // 取消按钮
                    Button("取消") {
                        showingTimeSuggestion = false
                    }
                    .foregroundColor(.secondary)
                    .padding(.horizontal, 20)
                    .padding(.vertical, 10)
                    .background(Color.gray.opacity(0.2))
                    .cornerRadius(8)
                    
                    // 确认按钮
                    Button("确认") {
                        confirmSuggestedTime()
                        showingTimeSuggestion = false
                    }
                    .foregroundColor(.white)
                    .padding(.horizontal, 20)
                    .padding(.vertical, 10)
                    .background(Color.blue)
                    .cornerRadius(8)
                }
            }
            .padding(24)
            .background(Color(.systemBackground))
            .cornerRadius(16)
            .shadow(radius: 10)
            .padding(.horizontal, 40)
        }
        .animation(.easeInOut(duration: 0.3), value: showingTimeSuggestion)
    }
    
    private func loadAvailableTimes() {
        // 模拟加载可用时间
        let calendar = Calendar.current
        let now = Date()
        let startOfDay = calendar.startOfDay(for: selectedDate)
        
        // 计算30分钟后的时间作为最早可预订时间
        let minimumBookingTime = calendar.date(byAdding: .minute, value: 30, to: now) ?? now
        
        var times: [Date] = []
        
        // 生成时间段（11:00 - 21:00，每30分钟一个时间段）
        for hour in 11...20 {
            for minute in [0, 30] {
                if let time = calendar.date(bySettingHour: hour, minute: minute, second: 0, of: startOfDay) {
                    // 如果是今天，只显示30分钟后的时间
                    if calendar.isDate(selectedDate, inSameDayAs: now) {
                        if time >= minimumBookingTime {
                            times.append(time)
                        }
                    } else {
                        // 如果是未来的日期，显示所有营业时间
                        times.append(time)
                    }
                }
            }
        }
        
        availableTimes = times
        
        // 如果当前选择的时间不在可用时间列表中，清除选择
        if let selectedTime = selectedTime, !availableTimes.contains(selectedTime) {
            self.selectedTime = nil
        }
    }
    
    private func formatTime(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        return formatter.string(from: date)
    }
    
    private func formatDate(_ date: Date) -> String {
        let formatter = DateFormatter()
        if dataManager.currentLanguage == "zh" {
            formatter.dateFormat = "MM月dd日"
        } else {
            formatter.locale = Locale(identifier: "en_US")
            formatter.dateFormat = "dd MMM"
        }
        return formatter.string(from: date)
    }
    
    private func formatDateShort(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "M/d"
        return formatter.string(from: date)
    }
    
    private func getAvailableSeats(for seatingType: ReservationConfig.SeatingType, at date: Date, time: Date?) -> Int {
        guard let time = time else { return seatingType.totalSeats }
        return ReservationConfig.SeatAvailability.getAvailableSeats(for: seatingType, at: date, time: time, partySize: selectedPartySize, dataManager: dataManager)
    }
    
    // MARK: - 新增的时间轴和日期选择器辅助方法
    
    /// 获取可用的时间段（10分钟间隔，在营业时间内，过滤掉不可预订的时间）
    private func getAvailableTimeSlots() -> [Int] {
        var timeSlots: [Int] = []
        let calendar = Calendar.current
        let now = Date()
        
        // 计算30分钟后的时间作为最早可预订时间
        let minimumBookingTime = calendar.date(byAdding: .minute, value: 30, to: now) ?? now
        
        // 获取当天的营业时间
        let businessHours = BusinessHoursManager.getBusinessHoursForDate(selectedDate)
        
        for timeSlot in businessHours {
            let startHour = calendar.component(.hour, from: timeSlot.start)
            let startMinute = calendar.component(.minute, from: timeSlot.start)
            let endHour = calendar.component(.hour, from: timeSlot.end)
            let endMinute = calendar.component(.minute, from: timeSlot.end)
            
            let startTotalMinutes = startHour * 60 + startMinute
            let endTotalMinutes = endHour * 60 + endMinute
            
            // 生成10分钟间隔的时间段
            var currentMinutes = startTotalMinutes
            while currentMinutes < endTotalMinutes {
                // 创建对应的时间对象进行比较
                if let timeDate = calendar.date(bySettingHour: currentMinutes / 60, minute: currentMinutes % 60, second: 0, of: selectedDate) {
                    // 如果是今天，只显示30分钟后的时间
                    if calendar.isDate(selectedDate, inSameDayAs: now) {
                        if timeDate >= minimumBookingTime {
                            timeSlots.append(currentMinutes)
                        }
                    } else {
                        // 如果是未来的日期，显示所有营业时间
                        timeSlots.append(currentMinutes)
                    }
                }
                currentMinutes += 10
            }
        }
        
        return timeSlots.sorted()
    }
    
    /// 格式化时间段显示
    private func formatTimeSlot(_ totalMinutes: Int) -> String {
        let hour = totalMinutes / 60
        let minute = totalMinutes % 60
        return String(format: "%02d:%02d", hour, minute)
    }
    
    /// 格式化日期选择器显示
    private func formatDateForPicker(_ date: Date) -> String {
        let formatter = DateFormatter()
        
        if dataManager.currentLanguage == "zh" {
            formatter.dateFormat = "M月d日"
            formatter.locale = Locale(identifier: "zh_CN")
        } else {
            formatter.dateFormat = "dd MMM"
            formatter.locale = Locale(identifier: "en_US")
        }
        
        // 直接显示日期，不再显示"今天"、"明天"
        return formatter.string(from: date)
    }
    
    /// 初始化可用日期（未来30天）
    private func initializeAvailableDates() {
        let calendar = Calendar.current
        var dates: [Date] = []
        
        for i in 0..<30 {
            if let date = calendar.date(byAdding: .day, value: i, to: Date()) {
                dates.append(date)
            }
        }
        
        availableDates = dates
        
        // 设置默认选中明天（索引1）
        if availableDates.count > 1 {
            selectedDateIndex = 1
            selectedDate = availableDates[1]
        } else if !availableDates.isEmpty {
            selectedDateIndex = 0
            selectedDate = availableDates[0]
        }
    }
    
    /// 更新选中的时间
    private func updateSelectedTime() {
        let calendar = Calendar.current
        
        if let newDate = calendar.date(bySettingHour: selectedHour, minute: selectedMinute, second: 0, of: selectedDate) {
            // 对于堂食预订，检查座位可用性并提供时间建议
            if selectedOrderType == .reservationDineIn {
                checkSeatAvailabilityAndSuggestTime(for: newDate)
            } else {
                selectedTime = newDate
            }
        }
    }
    
    /// 设置默认的第一个可用时间
    private func setDefaultAvailableTime() {
        let availableSlots = getAvailableTimeSlots()
        if let firstAvailableSlot = availableSlots.first {
            selectedHour = firstAvailableSlot / 60
            selectedMinute = firstAvailableSlot % 60
            updateSelectedTime()
        }
    }
    
    /// 检查座位可用性并建议时间
    private func checkSeatAvailabilityAndSuggestTime(for requestedTime: Date) {
        // 只对堂食预订进行座位可用性检查，外带预订不受座位限制
        if selectedOrderType.isDineIn {
            if ReservationConfig.SeatAvailability.hasAvailableSeats(
                for: selectedSeatingType,
                at: selectedDate,
                time: requestedTime,
                partySize: selectedPartySize,
                dataManager: dataManager
            ) {
                // 有可用座位，直接设置时间
                selectedTime = requestedTime
                showingTimeSuggestion = false
            } else {
                // 没有可用座位，建议下一个可用时间
                if let nextAvailableTime = ReservationConfig.SeatAvailability.getNextAvailableTime(
                    for: selectedSeatingType,
                    at: selectedDate,
                    after: requestedTime,
                    partySize: selectedPartySize,
                    dataManager: dataManager
                ) {
                    suggestedTime = nextAvailableTime
                    let timeFormatter = DateFormatter()
                    timeFormatter.dateFormat = "HH:mm"
                    let requestedTimeStr = timeFormatter.string(from: requestedTime)
                    let suggestedTimeStr = timeFormatter.string(from: nextAvailableTime)
                    let seatingTypeName = dataManager.currentLanguage == "zh" ? selectedSeatingType.chineseName : selectedSeatingType.englishName
                    
                    timeSuggestionMessage = dataManager.currentLanguage == "zh" ? 
                        "\(requestedTimeStr) 的\(seatingTypeName)座位已满，可否帮您预订 \(suggestedTimeStr) 的位置？" :
                        "\(seatingTypeName) seats at \(requestedTimeStr) are full. Would you like to book at \(suggestedTimeStr) instead?"
                    
                    showingTimeSuggestion = true
                } else {
                    // 当天没有更多可用时间
                    selectedTime = requestedTime
                    showingTimeSuggestion = false
                }
            }
        } else {
            // 外带预订不受座位限制，直接设置时间
            selectedTime = requestedTime
            showingTimeSuggestion = false
        }
    }
    
    /// 确认建议的时间
    private func confirmSuggestedTime() {
        if let suggested = suggestedTime {
            let calendar = Calendar.current
            selectedHour = calendar.component(.hour, from: suggested)
            selectedMinute = calendar.component(.minute, from: suggested)
            selectedTime = suggested
        }
        showingTimeSuggestion = false
    }
    
    // MARK: - 座位可用性检查
    private func checkSeatAvailabilityForCurrentSelection() {
        guard selectedOrderType.isDineIn && selectedOrderType.isReservation else { return }
        
        let currentDate = selectedDate
        let availableSeats = getAvailableSeats(for: selectedSeatingType, at: currentDate, time: nil)
        
        if selectedPartySize > availableSeats {
            let seatingTypeName = dataManager.currentLanguage == "zh" ? 
                (selectedSeatingType == .indoor ? "室内" : "室外") : 
                (selectedSeatingType == .indoor ? "Indoor" : "Outdoor")
            
            seatAvailabilityWarningMessage = dataManager.currentLanguage == "zh" ? 
                "抱歉，\(seatingTypeName)座位当前只有 \(availableSeats) 个可用座位，无法满足 \(selectedPartySize) 人的需求。请减少人数或选择其他座位类型。" : 
                "Sorry, \(seatingTypeName) seating currently has only \(availableSeats) available seats, which cannot accommodate \(selectedPartySize) people. Please reduce the party size or choose a different seating type."
            
            showingSeatAvailabilityWarning = true
        }
    }
    
    // MARK: - 座位可用性警告弹窗
    private var seatAvailabilityWarningOverlay: some View {
        ZStack {
            // 背景遮罩
            Color.black.opacity(0.4)
                .ignoresSafeArea()
                .onTapGesture {
                    showingSeatAvailabilityWarning = false
                }
            
            // 警告弹窗
            VStack(spacing: 20) {
                Text(dataManager.currentLanguage == "zh" ? "座位不足" : "Insufficient Seats")
                    .font(.title2)
                    .fontWeight(.bold)
                    .foregroundColor(.primary)
                
                Text(seatAvailabilityWarningMessage)
                    .font(.body)
                    .multilineTextAlignment(.center)
                    .foregroundColor(.secondary)
                    .padding(.horizontal)
                
                Button(dataManager.currentLanguage == "zh" ? "知道了" : "Got it") {
                    showingSeatAvailabilityWarning = false
                }
                .foregroundColor(.white)
                .padding(.horizontal, 20)
                .padding(.vertical, 10)
                .background(Color.orange)
                .cornerRadius(8)
            }
            .padding(24)
            .background(Color(.systemBackground))
            .cornerRadius(16)
            .shadow(radius: 10)
            .padding(.horizontal, 40)
        }
        .animation(.easeInOut(duration: 0.3), value: showingSeatAvailabilityWarning)
    }
    
    private var businessHoursWarningOverlay: some View {
        ZStack {
            // 背景遮罩
            Color.black.opacity(0.4)
                .ignoresSafeArea()
                .onTapGesture {
                    showingBusinessHoursWarning = false
                }
            
            VStack(spacing: 20) {
                Text(dataManager.currentLanguage == "zh" ? "非营业时间" : "Outside Business Hours")
                    .font(.title2)
                    .fontWeight(.bold)
                    .foregroundColor(.primary)
                
                Text(businessHoursWarningMessage)
                    .font(.body)
                    .multilineTextAlignment(.center)
                    .foregroundColor(.secondary)
                    .padding(.horizontal)
                
                Button(dataManager.currentLanguage == "zh" ? "知道了" : "Got it") {
                    showingBusinessHoursWarning = false
                }
                .foregroundColor(.white)
                .padding(.horizontal, 20)
                .padding(.vertical, 10)
                .background(Color.orange)
                .cornerRadius(8)
            }
            .padding(24)
            .background(Color(.systemBackground))
            .cornerRadius(16)
            .shadow(radius: 10)
            .padding(.horizontal, 40)
        }
        .animation(.easeInOut(duration: 0.3), value: showingBusinessHoursWarning)
    }
    
    /// 显示营业时间警告
    private func showBusinessHoursWarning(message: String) {
        businessHoursWarningMessage = message
        showingBusinessHoursWarning = true
    }
    
    /// 检查并设置预订的默认时间
    private func checkAndSetDefaultTimeForReservation() {
        let calendar = Calendar.current
        let currentHour = calendar.component(.hour, from: Date())
        let currentMinute = calendar.component(.minute, from: Date())
        
        // 设置默认时间为当前时间（向上取整到最近的10分钟间隔）
        let roundedMinute = ((currentMinute + 9) / 10) * 10
        var defaultHour = currentHour
        var defaultMinute = roundedMinute
        
        if defaultMinute >= 60 {
            defaultHour += 1
            defaultMinute = 0
        }
        
        // 确保时间在营业时间内
        if defaultHour < 11 {
            defaultHour = 11
            defaultMinute = 0
        } else if defaultHour >= 22 {
            // 如果已经过了营业时间，设置为明天的11:00
            selectedDate = calendar.date(byAdding: .day, value: 1, to: selectedDate) ?? selectedDate
            defaultHour = 11
            defaultMinute = 0
        }
        
        selectedHour = defaultHour
        selectedMinute = defaultMinute
        
        // 创建默认时间
        if let defaultTime = calendar.date(bySettingHour: defaultHour, minute: defaultMinute, second: 0, of: selectedDate) {
            // 检查默认时间的座位可用性
            if ReservationConfig.SeatAvailability.hasAvailableSeats(
                for: selectedSeatingType,
                at: selectedDate,
                time: defaultTime,
                partySize: selectedPartySize,
                dataManager: dataManager
            ) {
                // 默认时间有可用座位，直接设置
                selectedTime = defaultTime
            } else {
                // 默认时间没有可用座位，寻找下一个可用时间
                if let nextAvailableTime = ReservationConfig.SeatAvailability.getNextAvailableTime(
                    for: selectedSeatingType,
                    at: selectedDate,
                    after: defaultTime,
                    partySize: selectedPartySize,
                    dataManager: dataManager
                ) {
                    // 找到可用时间，自动设置
                    selectedTime = nextAvailableTime
                    
                    // 更新时间选择器的显示
                    let nextHour = calendar.component(.hour, from: nextAvailableTime)
                    let nextMinute = calendar.component(.minute, from: nextAvailableTime)
                    selectedHour = nextHour
                    selectedMinute = nextMinute
                } else {
                    // 当天没有可用时间，设置为nil
                    selectedTime = nil
                }
            }
        }
    }
}

// MARK: - 免责声明视图
struct DisclaimerView: View {
    @EnvironmentObject var dataManager: DataManager
    @Binding var isAccepted: Bool
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(alignment: .leading, spacing: 20) {
                    Text(dataManager.currentLanguage == "zh" ? "预订条款与说明" : "Reservation Terms & Conditions")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                    
                    VStack(alignment: .leading, spacing: 16) {
                        let terms = dataManager.currentLanguage == "zh" ? ReservationConfig.Localization.reservationTerms_zh : ReservationConfig.Localization.reservationTerms_en
                        ForEach(Array(terms.enumerated()), id: \.offset) { index, term in
                            HStack(alignment: .top, spacing: 8) {
                                Text("\(index + 1).")
                                    .font(.system(size: 14, weight: .medium, design: .rounded))
                                    .foregroundColor(.white.opacity(0.9))
                                    .frame(width: 20, alignment: .leading)
                                
                                Text(term)
                                    .font(.system(size: 14, weight: .medium, design: .rounded))
                                    .foregroundColor(.white.opacity(0.9))
                                    .multilineTextAlignment(.leading)
                                    .fixedSize(horizontal: false, vertical: true)
                                
                                Spacer()
                            }
                        }
                    }
                    
                    Spacer(minLength: 40)
                    
                    Button(action: {
                        isAccepted = true
                        presentationMode.wrappedValue.dismiss()
                    }) {
                        HStack {
                            Image(systemName: "checkmark.circle.fill")
                            Text(dataManager.currentLanguage == "zh" ? "我已阅读并同意以上条款" : "I have read and agree to the terms")
                        }
                        .font(.headline)
                        .foregroundColor(.white)
                        .frame(maxWidth: .infinity)
                        .frame(height: 50)
                        .background(
                            LinearGradient(
                                colors: [Color.orange, Color.red],
                                startPoint: .leading,
                                endPoint: .trailing
                            )
                        )
                        .cornerRadius(25)
                    }
                }
                .padding(20)
            }
            .background(
                LinearGradient(
                    colors: [
                        Color(red: 0.12, green: 0.12, blue: 0.12),
                        Color(red: 0.18, green: 0.16, blue: 0.15)
                    ],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
            )
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button(dataManager.currentLanguage == "zh" ? "关闭" : "Close") {
                        presentationMode.wrappedValue.dismiss()
                    }
                    .foregroundColor(.orange)
                }
            }
        }
    }
    
    private func disclaimerItem(text: String) -> some View {
        HStack(alignment: .top, spacing: 12) {
            Circle()
                .fill(Color.orange)
                .frame(width: 6, height: 6)
                .padding(.top, 6)
            
            Text(text)
                .font(.body)
                .foregroundColor(.white.opacity(0.9))
                .multilineTextAlignment(.leading)
            
            Spacer()
        }
    }
}

// MARK: - 预览
struct ReservationFlowView_Previews: PreviewProvider {
    static var previews: some View {
        ReservationFlowView(
            isPresented: .constant(true),
            onReservationConfirmed: { _ in },
            onImmediateDineIn: nil,
            onImmediateTakeAway: nil
        )
        .environmentObject(DataManager.shared)
    }
}